;(function ( $, window, undefined ) {
	//装载组件
	Core.use('template', 'fancybox', 'uploadify',
			 'JS:plugins/artZoom/artZoom.js',
			 'JS:plugins/placeholder.js',
			 'JS:plugins/mousewheel.js', function(){

		$('#' + uploadSettings.id).uploadify($.extend({
			swf: Core.path('JS:plugins/uploadify/uploadify.swf'),
			itemTemplate : template.render('uploadQueuedTemplate'),
			width: 76,
			height: 28,
			
			fileSizeLimit : 20*1024,
			fileTypeExts : "*.jpg;*.jpeg;*.gif;*.png",
			fileTypeDesc: "jpg, gif, png等图片文件",
			
			overrideEvents: ['onUploadProgress', 'onUploadSuccess', 'onUploadComplete'],
			
			onSWFReady: function(){
				var _this = this;
				var obj = _this.wrapper.data('uploadify');
				setUploadTip(_this.settings.uploadLimit, getQuenedLength());
				//提交表单
				$('#' + _this.settings.uploadID).click(function(){
					if(obj.queueData.queueLength>0){
						var form = $('#' + _this.settings.formID),
							uploadBtn = $('#' +_this.settings.uploadID);
						Core.Util.btnDisable(uploadBtn);
						form.submit();
					}else{
						alert('你还没有添加图片,请先添加图片吧');
					}
				});
			},
			onDialogClose: function(queueData){
				$('#' + this.settings.uploadID).attr('disabled', !(getQuenedLength() > 0));
				
			},
			onUploadStart: function(file){
				var message = $('#' + file.id).find('.message');
				message.html(message.attr('date-progress'));
			},
			onUploadProgress: function(file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded, uploadSize){
				var percent = Math.ceil((fileBytesLoaded / fileTotalBytes) * 100);
				$('#' + file.id).find('.progress .bar').css('width', percent + "%");
			},
			onUploadSuccess: function(file, serverData, response){
				var data = $.parseJSON(serverData);
				if(data.success && data.message){
					data = data.message;
					var _this = this,
						rotateValue = 0,
						item = $('#' + file.id),
						form = item.find('[name]'),
						formName = item.find('#name'),
						formRotate = item.find('#rotate'),
						formPath = item.find('#path'),
						thumb = item.find('.thumbnail'),
						status = item.find('.photo-status'),
						zoomBtn = item.find('#zoomBtn'),
						removeBtn = item.find('#removeBtn'),
						rotateBtn = item.find('#rotateBtn');
					
					// 显示缩略图
					thumb.attr('src', data.thumbUrl);

					//图片旋转
					thumb.data('rotate', 0);
					rotateBtn.click(function(){
						rotateValue += 90;
						rotateValue = rotateValue === 360 ? 0 : rotateValue;
						$.imgRotate(thumb[0], rotateValue);
						thumb.data('rotate', rotateValue);
						formRotate.val(rotateValue);
					});
					
					// 点击查看大图片
					zoomBtn.fancybox({
						live: false,
						type: 'image',
						href: data.url,
						title: function(){
							return formName.val();
						},
						beforeShow: function (){
							var zoomImg = this.wrap.find('.fancybox-image'),
								rotateValue = thumb.data('rotate');
							if($.inArray(rotateValue, [90, 270]) >= 0){
								var width = this.width,
									height = this.height;
								this.width = height;
								this.height = width;
							}
							$.imgRotate(zoomImg[0], rotateValue);
						}
					});
					
					//填充图片地址
					formPath.val(data.path);
					//填充 表单值
					formName.val(file.name);
					//更新表单选项的name值, 并增加IE placeholder支持
					form.attr('name', function(){
						return this.name.replace('[', '[' +file.id + '][');
					});

					//IE 的placeholder支持
					form.placeholder();
					
					//设置取消(删除)事件
					removeBtn.click(function(){
						if(confirm(removeBtn.attr('data-alert') || '确认删除?')){
							var limit = _this.settings.uploadLimit,
								hasLimit = getQuenedLength();
							if(hasLimit > 0){ //swfupload没有已上传文件删除功能.所以只能添加uploadLimit方式hack...
								_this.setFileUploadLimit( _this.settings.file_upload_limit - 0 + 1 );
								var a = _this;
								hasLimit--;
							}
							_this.wrapper.uploadify('cancel', file.id);
							setUploadTip(limit, hasLimit);
							$('#' + _this.settings.uploadID).attr('disabled', !(hasLimit > 0));
						}
					});
					setUploadTip(_this.settings.uploadLimit, getQuenedLength());
					//状态框隐藏
					status.fadeOut(2000);
				}else{
					alert(file.name + '上传失败');
				}
			},
			onUploadError : function(file, errorCode, errorMsg, errorString){
				alert(file.name + '上传失败, 错误信息:' + errorString);
			},
			onUploadComplete: function(){}
		}, uploadSettings), {
			button_image_url: Core.path('IMG:blank.gif')
		});
		
		function getQuenedLength(){
			return $('#uploadQueue .queue').length;
		}
		
		function setUploadTip(limit, hasLimit){
			if(!limit) return ;
			if(hasLimit){
				$('#uploadTip').html('已添加' + hasLimit + '张，最多还可以添加' + (limit - hasLimit) + '张');
			}else{
				$('#uploadTip').html('每次最多可以添加' + limit + '张图片');
			}
		}
		
	});
})( jQuery, window);